import dayjs from 'dayjs';
import Date7Day from '../type';

/**
 * 对给定的时间戳转换比如 2023-10-11 23:20:48.123 转换为 2023-10-11 00:00:00.000
 * @param timestamp 给定时间戳
 * @returns 新的时间戳
 */
function getNewTimestamp(timestamp?: number | string): number {
  return timestamp
    ? dayjs(timestamp).hour(0).minute(0).second(0).millisecond(0).valueOf()
    : dayjs().hour(0).minute(0).second(0).millisecond(0).valueOf();
}

export default function use7Day() {
  //一天的时间戳
  const oneDayTimestamp = 24 * 60 * 60 * 1000;
  const date7Day: Date7Day[] = [];
  /**
   * 给定时间戳后7天
   * 将当天的时间设置为比如: 2010-10-20 00:00:00.000
   * @param timestamp 时间戳
   */
  function date7DayByTimestamp(timestamp: Number) {
    date7Day.splice(0, date7Day.length);
    const currentDayTimestamp = getNewTimestamp(timestamp.valueOf());
    for (let i = 0; i < 7; i++) {
      const iDayAfterTimestamp = currentDayTimestamp + i * oneDayTimestamp;
      const date = new Date(iDayAfterTimestamp);
      const year = date.getFullYear().toString();
      const month = (date.getMonth() + 1).toString();
      const day = date.getDate().toString();
      date7Day.push({
        year: year,
        month: month,
        day: day,
        timestamp: iDayAfterTimestamp,
      });
    }
  }

  return { date7DayByTimestamp, date7Day, getNewTimestamp };
}
